package com.world.cat.controller.sys;

import com.world.cat.app.AppConstant;
import com.world.cat.pojo.TreeNode;
import com.world.cat.service.sys.AreaService;
import com.world.common.pojo.WorldPage;
import com.world.common.pojo.Result;
import com.world.common.util.json.DateJsonValueProcessor;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.world.cat.model.sys.Area;

@Controller
@RequestMapping(value = "/sys/area")
public class AreaController {
    @Resource
    private AreaService service;

    @RequestMapping(value = "/home")
    public String home(Model model) {
        return "/sys/area/home";
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String params, WorldPage worldPage, int page, int rows) throws Exception {
        worldPage.setPageIndex(page);
        worldPage.setPageSize(rows);
        worldPage.setProperties("createTime");
        Page<Area> pages = service.findPage(Area.class, params, worldPage.getPageRequest());
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("total", pages.getTotalElements());
        jsonMap.put("rows", pages.getContent());
        return jsonMap;
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Object save(String params) throws Exception {
        service.save(Area.class, params);
        return new Result(true);
    }

    @RequestMapping(value = "/del")
    @ResponseBody
    public Object del(String[] ids) {
        service.del(ids);
        return new Result(true);
    }

    @RequestMapping(value = "/edit")
    @ResponseBody
    public Object edit(String id) throws Exception {
        Area object = service.get(id);
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject jsonObject = JSONObject.fromObject(object, config);
        return new Result(true, "", jsonObject.toString());
    }

    @RequestMapping(value = "/areaTree", name = "获得区域树")
    @ResponseBody
    public Object areaTree(String userId) throws Exception {
        TreeNode node = service.getAreaTree(userId,  AppConstant.areaRoot);
        List<TreeNode> nodes = new ArrayList<>();
        nodes.add(node);
        return nodes;
    }
}
